<template>
    <video ref="video" :id="id" class="cmp cmp-videojs video-js vjs-default-skin" controls playsinline autoplay="autoplay">
      <source :src="videoUrl" type="application/x-mpegURL" />
    </video>
</template>

<script>
let videojs = global.videojs || {}

export default {
  name: 'cmp-videojs',
  props: {
    videoUrl: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
        id: 'player_' + `${Math.random()}`.substring(2),
        videoObj: null,
        options: {
            autoplay: false, // 设置自动播放
            muted: false, // 设置为true才可实现自动播放,同时视频也被静音（Chrome66及以上版本，禁止音视频的自动播放）
            preload: 'auto', // 预加载
            controls: true, // 显示播放的控件
            playbackRates: [0.5, 1, 1.5, 2]
        }
    }
  },
  beforeDestroy () {
    this.videoObj && this.videoObj.dispose()
  },
  methods: {
    // 播放
    play () {
        if (!this.videoUrl) {
            this.$toast('请输入视频地址')
            return
        }
        // if (/\.m3u8$/.test(this.videoUrl.split('?')[0])) {
        //     this.$toast('请输入m3u8格式的视频地址')
        //     return
        // }
        this.destroy()
        if (!this.videoObj) {
            if (!this.$refs.video) return
            this.videoObj = videojs(this.id, this.options)
        } else {
            this.videoObj.src(this.videoUrl)
        }
        this.$nextTick(() => {
            this.videoObj.play()
        })
    },
    // 暂停
    pause () {
        this.videoObj && this.videoObj.pause()
    },
    // 销毁
    destroy () {
        this.videoObj && this.videoObj.pause()
    }
  }
}
</script>

<style scoped lang="less">
@import "~@/assets/css/_mixins.less";
@import "~@/assets/css/_color.less";
.cmp-videojs {
    display: block;
    width: 100%;
    height: 100%;
    background-color: #333;
}
</style>
